package com.wjf.birdfish.hibernate;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class PageImplForHql<T> extends AbstractPage<T> {
	private Query query;

	protected PageImplForHql(Session session, int pageSize, String queryString, Object[] params) {
		if (pageSize > 0) {
			this.pageSize = pageSize;
		}
		recordNumber = getRecordNumber(session, queryString, params);
		setPageNumber();
		query = session.createQuery(initQueryParams(params, queryString));
	}

	private int getRecordNumber(Session session, String queryString, Object[] params) {
		Query countQuery = session.createQuery(generateCountHql(initQueryParams(params, queryString)));
		Object orn = countQuery.uniqueResult();
		return (orn == null) ? 0 : Integer.parseInt(orn.toString());
	}

	private String initQueryParams(Object[] params, String query) {
		if (params == null) {
			return query;
		}
		return String.format(query.replace("?", "'%s'"), params);
	}

	private String generateCountHql(String hql) {
		String lql = hql.trim().toUpperCase();
		int index = lql.indexOf("ORDER BY");
		String query = (index == -1) ? hql : hql.substring(0, index).trim();
		if (lql.startsWith("SELECT")) {
			query = query.substring(lql.indexOf("FROM"));
		}
		return "select count(*) " + query;
	}

	@SuppressWarnings("unchecked")
	public List<T> getData() {
		query.setFirstResult(computeFirstResult());
		query.setMaxResults(computeMaxResults());
		if (data == null) {
			data = query.list();
		}
		return data;
	}

}
